<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
  * Licence Agreement
*/

/**
  * User Controller
*/

class Controller_User extends Controller_Template_Login {

  /**
   * User Index Page
   *
   */
  public function action_index()
  {

    // Attempt to auto-login the user, if they have chosen that option
    Auth::instance()->auto_login();

  	if (Auth::instance()->logged_in())
  	{
	
      // The user is logged in
  	  $user = Auth::instance()->get_user();
	  
	  $errors = array();
	  $this->template->set('title', __('Log On'));
	  $this->template->set('header_text', __('Log On'));
	  $this->template->set('content', new View('user/success'));
	  $this->template->content->bind('fields', $_POST);
	  $this->template->content->bind('errors', $errors);

  	}
  	else
  	{
  	  // The user is not logged in, so redirect them to the login page
      Request::instance()->redirect('user/login');
  	}
  }

  /**
   * Create a new user account
   *
   */
  public function action_create()
  {
    $errors = array();

    $this->template->set('title', __('Create an account'));
    $this->template->set('header_text', __('Create an account'));
   	$this->template->set('content', new View('user/create'));
   	$this->template->content->bind('fields', $_POST);  // Populate the field data with submitted data so the user doesn't have to re-enter it if there's an error
   	$this->template->content->bind('errors', $errors);

    // ensure that a token was submitted and matches the token in the session, provides some basic security against CSFR
    if (isset($_POST['submit']) && (empty($_POST['token']) || $_POST['token'] !== $this->session->get('token')))
    {
      $errors[] = __('Form token not set or invalid');
      unset($_POST['submit']);
    }
    unset($_POST['token']);

    if (isset($_POST['submit']))
    {
      // Assign values from _POST individually to prevent malicious form submission
      // NOTE: Future versions of Sprig may allow limitation to 'editable' fields only, in which case this step will be un-necessary
    	$user = Sprig::factory('user')
    	          ->values(array('email'     => $_POST['email'],
    	                         'username'  => $_POST['email'],     // Username is email address for this purpose
    	                         'password'  => $_POST['password'],
    	                         'password_confirm'  => $_POST['password_confirm'],
    	                         'logins'    => 0,
								 'validated' => 0));
    	

      try
      {
        // All customers must have the 'login' role
    	$user->roles = array(Sprig::factory('Role')->values(array('name' => 'login'))->load()->id);
        $user->create();

		$user_email = $user->email;
        
		// log the user in and get the user id from the session data
    	Auth::instance()->force_login($user_email);
		$user = Session::instance()->get('auth_user', NULL);

		$userdetail = Sprig::factory('userdetail')
						->values(array('user'	   => $user->id,
									   'firstname' => $_POST['firstname'],
									   'lastname'  => $_POST['lastname']
									  ));
		$userdetail->create();
		
		//send the varification email
		$this->_send_validation_email($user_email);
		
		Request::instance()->redirect('user/validate');
    	}
    	catch (Validate_Exception $e)
    	{
    	  $errors = $e->array->errors('user');
   	  }
    }

    // Create new token
    $token = Security::token();
    $this->session->set('token', $token);
    $this->template->content->set('token', $token);
  }

  /**
   * Validate the user
   *
   */
  public function action_validate() {
	
    $errors = array();
	$captcha = Captcha::instance();

	// get user details
	$user = Session::instance()->get('auth_user', NULL);
	$user_email = $user->email;
	

	$this->template->set('title', __('Validate'));
    $this->template->set('header_text', __('Validate'));
   	$this->template->set('content', new View('user/validate'));
	
	if (isset($_POST['resend']))
	{
		$this->_send_validation_email($user_email);
		$errors[] = __('Varification code has been resent');
	}
	
	if (isset($_POST['submit']))
	{
		// use the first 8 characters of a hash created with the user's email address
		$varification_code = $this->_get_validation_code($user_email);
		
		if (isset($_POST['captcha']) && $_POST['validate'] && Captcha::valid($_POST['captcha']))
		{
			if ($_POST['validate'] == $varification_code)
			{
				$user = Sprig::factory('user')
						  ->values(array('validated' => 1));
				$user->update();
				
				Request::instance()->redirect('user/index');
			}
			else
			{	
				echo $_POST['validate'];
				$errors[] = __('Incorrect validation code entered');
			}
		}
		else
		{
			$errors[] = __('Please re-enter the required information');
		}
	}
	
	$this->template->content->bind('errors', $errors);
	$this->template->content->bind('user_email', $user_email);
   	$this->template->content->bind('captcha', $captcha);
	
  }
  
  /**
   * Logout the current user
   *
   */
  public function action_logoff() {
    Auth::instance()->logout();

    $this->template->set('title', __('Log Off'));
    $this->template->set('header_text', __('Log Off'));
   	$this->template->set('content', new View('user/logoff'));
  }

  /**
   * Allow the user to login
   *
   */
  public function action_login() {
    if (Auth::instance()->auto_login())
    {
      // The user is already logged in so just send them to the account index page.
      Request::instance()->redirect('user/index');
    }

    $errors = array();
    $this->template->set('title', __('Log On'));
    $this->template->set('header_text', __('Log On'));
   	$this->template->set('content', new View('user/login'));
   	$this->template->content->bind('fields', $_POST);
   	$this->template->content->bind('errors', $errors);

   	// ensure that a token was submitted and matches the token in the session, provides some basic security against CSFR
    if (isset($_POST['submit']) && (empty($_POST['token']) || $_POST['token'] !== $this->session->get('token')))
    {
      $errors[] = __('Form token not set or invalid');
      unset($_POST['submit']);
    }
    unset($_POST['token']);

    $token = Security::token();
    $this->session->set('token', $token);
    $this->template->content->set('token', $token);

    if (isset($_POST['submit']))
    {
      if (Arr::get($_POST,'new_user') === 'true')
      {
        unset($_POST['submit']);
      	Request::instance()->response = Request::factory('user/create')
      	                                   ->execute();
        $this->auto_render = FALSE;
      }
      else
      {
        $remember = Arr::get($_POST, 'remember_me') == 'on' ? TRUE : FALSE;
		Auth::instance()->login($_POST['email'], $_POST['password'], $remember);
        if ( Auth::instance()->logged_in() )
      	{
      	  Request::instance()->redirect('user/index');
      	}
      	else
      	{
      	 $errors[] = __('Sorry, but we were unable to confirm your email address and / or password. Please check and try again.');
      	}
      }
    }
  }

  /**
   * Send validation email
   *
   */
  public function _send_validation_email($user_email) {
  		
		// get the email template
		$this->template->set('email', new View('user/validate_email'));
		
		// get the varification code
		
		$varification_code = $this->_get_validation_code($user_email);
		
		$this->template->email->bind('varification_code', $varification_code);
		
		// send the email
		$email_to		= $user_email;
		$email_subject	= __('Varification Code');
		$email_message	= $this->template->email;
		$email_headers	= 'From: noreply@logon.info' . "\r\n" .
						  'Reply-To: noreply@logon.info' . "\r\n" .
						  'X-Mailer: PHP/' . phpversion();
		
		mail($email_to, $email_subject, $email_message, $email_headers);

  }
  
  /**
   * Get validation code
   *
   */
  public function _get_validation_code($user_email) {
	
	// use the first 8 characters of a hash created with the user's email address
	$varification_code = substr(hash("md5", $user_email), 0, 7);
	
	return $varification_code;
  }
}